const express = require('express');
const router = express.Router();
const database = require('./database');

// 获取所有公司
router.get('/companies', async (req, res) => {
    try {
        const [rows] = await database.query('SELECT * FROM companies');
        res.json(rows);
    } catch (err) {
        console.error('Error getting companies:', err);
        res.status(500).json({ error: 'Error getting companies' });
    }
});

// 添加新公司
router.post('/companies', async (req, res) => {
    const newCompany = {
        name: req.body.name || null,
        companyId: req.body.companyId || null
    };
    try {
        const query = 'INSERT INTO companies (name, companyId) VALUES (?, ?)';
        const [result] = await database.query(query, [newCompany.name, newCompany.companyId]);
        newCompany.id = result.insertId;
        res.status(201).json(newCompany);
    } catch (err) {
        console.error('Error inserting new company:', err.message);
        res.status(500).json({ error: 'Error inserting new company' });
    }
});

// 删除指定ID的公司
router.delete('/companies/:id', async (req, res) => {
    const { id } = req.params;
    try {
        const query = 'DELETE FROM companies WHERE id = ?';
        await database.query(query, [id]);
        res.status(204).end();
    } catch (err) {
        console.error('Error deleting company:', err);
        res.status(500).json({ error: 'Error deleting company' });
    }
});

module.exports = router;